<?php

namespace StudyBuddy\Controllers;

use StudyBuddy\UserFacebook;
use StudyBuddy\WebPage;
use StudyBuddy\Request;
use StudyBuddy\Responder;
use StudyBuddy\Cookie;
use StudyBuddy\UserGfc;
use StudyBuddy\OFacebook;

class Logout extends WebPage {
    const GFC_SIGNOUT = '
	<script src="http://www.google.com/jsapi"></script>
<script type="text/javascript">
  google.load("friendconnect", "0.8");
</script>
<div id="tools"><p class="larger">Logging out. Please wait...</p></div>
	<script>
	google.friendconnect.container.loadOpenSocialApi({
  site: "%s",
  onload: function(securityToken) {
    if (!window.timesloaded) {
      window.timesloaded = 1;
      google.friendconnect.requestSignOut();
    } else {
      window.timesloaded++;
    }
    if (window.timesloaded > 1) {
      window.top.location.href = "/";
    }
  }
});
	</script>
	
	';

    /**
     * Unsets all session variables and unsets some cookies
     * This is all that is needed to logout
     *
     * @param array $arrParams array or GET or POST parameters
     */
    public function main() {

        $this->oRegistry->Dispatcher->post($this, 'onBeforeUserLogout');


        /**
         * Don't forget about the 'dnd' cookies
         * that may have been set previosly
         * Whith dnd set to 1 a user may register
         * with external auth and will never
         * be asked to provide email address
         * This is designed so that a user may say, hey, don't
         * bother me with this again, I don't want to provide
         * an email address
         *
         * But once the user logges out
         * treat them as another guest!
         */
        $aDelete = array('uid', 'dnd');

        /**
         * If current viewer is logged in
         * with Google Friend Connect
         * then the logout process is somewhat
         * different: we need to delete user's fcauth cookie(s)
         *
         */
        if ($this->oRegistry->Viewer instanceof UserGfc) {

            $GfcSiteID = $this->oRegistry->Ini->GFC_ID;
            if (!empty($GfcSiteID)) {
                $gfc = sprintf(self::GFC_SIGNOUT, $GfcSiteID);
                $gfc = Responder::PAGE_OPEN . $gfc . Responder::PAGE_CLOSE;
                d('sending out GFC Logout page: ' . $gfc);

                $fcauthSession = 'fcauth' . $GfcSiteID . '-s';
                $fcauthRegular = 'fcauth' . $GfcSiteID;
                $aDelete[] = $fcauthSession;
                $aDelete[] = $fcauthRegular;
            }
        }

        d('logging out Facebook User');
        $aFB = $this->oRegistry->Ini->getSection('FACEBOOK');
        if (!empty($aFB) && !empty($aFB['APP_ID'])) {
            $fb_cookie = 'fbsr_' . $aFB['APP_ID'];
            d('deleting Facebook cookie ' . $fb_cookie . ' len: ' . strlen($fb_cookie));
            $aDelete[] = $fb_cookie;
            $oFacebook = new OFacebook(array(
                        'appId' => $aFB['APP_ID'],
                        'secret' => $aFB['APP_SECRET']
                    ));
            $oFacebook->destroySession();
        }

        d('Delete these cookies: ' . print_r($aDelete, 1));

        Cookie::delete($aDelete);

        /**
         * Get copy of user data
         * because we going to need
         * it's values AFTER the user loggs
         * out and after the $this->oViewer has been destroyed
         *
         */
        $aUser = $this->oRegistry->Viewer->getArrayCopy();
        $this->oRegistry->Viewer = null;
        
        session_destroy();
//        
//        $CookieInfo = session_get_cookie_params();
//        if ((empty($CookieInfo['domain'])) && (empty($CookieInfo['secure']))) {
//            setcookie(session_name(), '', time() - 3600, $CookieInfo['path']);
//        } elseif (empty($CookieInfo['secure'])) {
//            setcookie(session_name(), '', time() - 3600, $CookieInfo['path'], $CookieInfo['domain']);
//        } else {
//            setcookie(session_name(), '', time() - 3600, $CookieInfo['path'], $CookieInfo['domain'], $CookieInfo['secure']);
//        }
//        unset($_COOKIE[session_name()]);
//        
        $_SESSION = array();

        $this->oRegistry->Dispatcher->post($this, 'onUserLogout', $aUser);

        d('Logged out SESSION: ' . print_r($_SESSION, 1));

        /* if (Request::isAjax()) {
          $sLoginForm = \StudyBuddy\LoginForm::makeLoginForm($this->oRegistry);
          $arrJSON = array('message'=> $sLoginForm);
          d('sending json: '.$sLoginForm);
          Responder::sendJSON($arrJSON);
          } */

        /**
         * For Google Friend Connect sendout
         * the html with logout JavaScript - that's
         * the only right way to logout
         */
        if (isset($gfc)) {
            exit($gfc);
        }

        // logout facebook
        if(isset($fb_cookie)) {
//            $_COOKIE['fbsr_studybuddy'] = 'logout';
            Cookie::set('fbsr_studybuddy', 'logout');
        }
        Responder::redirectToPage('/index.php?logout=1');
    }

}
